package edu.citadel.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Static utility class that provides helper methods used to work
 * with Java Collection classes.
 */
public final class CollectionUtils {
    private CollectionUtils() {
    }

    /**
     * Creates a generic List based off of a pre-Java 5 List.
     *
     * @param list  List of Objects
     * @param klass Class to cast the List elements to
     *
     * @return Generic List of the specified type
     */
    public static <T> List<T> makeGeneric(List list, Class<T> klass) {
        List<T> newList = new ArrayList<T>();

        for (Object element : list) {
            newList.add(klass.cast(element));
        }

        return newList;
    }

    /**
     * Creates a generic Map based off of a pre-Java 5 Map.
     *
     * @param map        Map of Objects keyed by Objects
     * @param keyClass   Class to cast the Map keys to
     * @param valueClass Class to cast the Map values to
     *
     * @return Generic Map of the specified type
     */
    public static <K, V> Map<K, V> makeGeneric(Map map, Class<K> keyClass, Class<V> valueClass) {
        Map<K, V> newMap = new HashMap<K, V>();

        for (Object element : map.entrySet()) {
            Map.Entry entry = (Map.Entry) element;
            newMap.put(keyClass.cast(entry.getKey()), valueClass.cast(entry.getValue()));
        }

        return newMap;
    }
}
